<template>
  <div class="page-common-layout">
    <div class="page-common-content">
      <tool-bar>
        <template slot="toolBtn" slot-scope="scope">
          <a-button class="cu-btn-primary" icon="plus" @click="
                (e) => {
                  handleAdd(e.key, $refs.masterList.data);
                }">
							{{$ct("add","新增")}}
          </a-button>
          <!-- <a-button
            class="cu-btn-default"
            icon="edit"
            @click="handleEdit($refs.masterList.rows, $refs.masterList.data)"
            v-action:organizationEditDialog
            >编辑</a-button
          > -->
        </template>
      </tool-bar>
      <TreeGrid
          ref="masterList"
          :columns="masterColumns"
          :url="url"
          rowKey="uuid"
          :parameter="parameter"
          :showRowSelect="false"
          @rowClick="masterRowClick"
      >
        <template slot="renderRegionStatus" slot-scope="{ record }">
          <a-tag :color=" record.regionStatus === 1 || record.regionStatus === '1' ? 'green' : 'red'">
            {{ record.regionStatus === 1 || record.regionStatus === "1" ? $ct('enable','启用') : $ct('disable','禁用') }}
          </a-tag>
        </template>
        <span slot="renderAction" slot-scope="{ record }">
          <template>
            <a @click="handleEdit(record, $refs.masterList.data)">{{$ct("edit","编辑")}}</a>
            <span class="action-margin"></span>
            <a @click="handleSub(record)" class="action-delete">{{$ct("delete","删除")}}</a>
          </template>
        </span>
      </TreeGrid>
      <!--	新增编辑	 -->
      <edit-form
          :type="key"
          ref="masterModal"
          :visible="masterVisible"
          :loading="masterConfirmLoading"
          :model="masterMdl"
          @cancel="handleCancel()"
          @ok="handleOk()"
      />
    </div>
  </div>
</template>

<script>
  import {TreeGrid} from "@/components";
  import {treeGridMixin} from "@/mixins/treeGridMixin";
  import editForm from "./treeEdit";

  export default {
    name: "Table",
    components: {TreeGrid, editForm},
    mixins: [treeGridMixin],
    created(){
      this.getListByLevelId()
    },
    data() {
      return {
        masterColumns: [
          {
            title: "区域名称",
            align: "left",
            dataIndex: "regionName",
            width: 250,
          },
          {
            title: "区域编码",
            dataIndex: "regionCode",
          },
          {
            title: "区域状态",
            dataIndex: "regionStatus",
            scopedSlots: {customRender: "renderRegionStatus"},
          },
          {
            title: "排序",
            dataIndex: "regionSort",
						langCode: "sort"
          },
          {
            title: "操作",
            width: 150,
            align: "center",
            dataIndex: "action",
            scopedSlots: {customRender: "renderAction"},
          },
        ],
        masterVisible: false,
        masterConfirmLoading: false,
        masterMdl: null,
        // 查询参数
        masterQueryParam: {},
        url: {
          fathersUrl: "/system/sysAdministrativeRegion/getListDataBylevelId",
          // fathersUrl: "/mdata/organization/getListByPid",// 企业微信导入组织机构没有层级不能用上面的
          expandUrl: "/system/sysAdministrativeRegion/getListDataById",
          masterUpdate: "/system/sysAdministrativeRegion/update",
          masterDelete: "/system/sysAdministrativeRegion/deleteBatch",
          masterSaveRoot: "/system/sysAdministrativeRegion/save",
          masterSave: "/system/sysAdministrativeRegion/save",
          getListByKeywords: "/system/sysAdministrativeRegion/getListByKeywords",
          getDicItemByCode: "/system/sysAdministrativeRegion/getDicItemByCode",
        },
        parameter: {
          father: {
            levelId: 1
          },
          children: {},
        },
        key: "1",
        data:[]
      };
    },

    methods: {
      // 获取最外层级数据
      getListByLevelId() {
        this.rowKeys = null;
        this.$post(this.url.fathersUrl, 0).then((res) => {
          if (res.statusCode === 300) {
            this.$message.warn(res.message);
            return;
          }
          let list = [];
          if (res?.rows) {
            list = res.rows;
          } else {
            list = res;
          }
          const arr = [];
          list.forEach(function(item, index) {
            arr.push({
              ...item,
              children: item.state === "closed" ? [] : "",
            });
          });
          this.data = arr;
          if (this.data.length != 0 && this.data[0].children) {
            this.onExpand("1", this.data[0]);
          }
        });
      },
      // 展开获取子级数据
      onExpand(expanded, record) {
        this.spinning = true;
        return new Promise((resolve) => {
          // 判断是否有子级
          if (record.children.length > 0) {
            this.spinning = false;
            resolve();
            return;
          }
          let parameter = this.parameter.children;
          parameter.pid = record.id;
          this.$post(this.url.expandUrl, parameter)
            .then((res) => {
              const data = this.data;
              const children = res;
              this.dataLength += children.length;
              const dataMap = (items) => {
                items.find((value) => {
                  if (value.id === record.id) {
                    var array = [];
                    children.forEach(function(values, index) {
                      array.push({
                        ...values,
                        children:
                          values.state === "closed" || !values.state ? [] : "",
                      });
                    });
                    value.children = array;
                    return items;
                  }
                  if (value.children && value.children.length > 0) {
                    dataMap(value.children);
                  }
                });
              };
              dataMap(data || []);
              this.data = data;
              this.spinning = false;
              resolve();
            })
            .catch((err) => {
              console.log(err);
            });
        });
      },
      // 新增
      handleAdd: function (key, treeData, e) {
        this.key = '2'
        let form = {}
        this.masterMdl = null
        form = this.$refs.masterModal.form
        form.resetFields() // 清理表单数据（可不做）
        this.masterVisible = true
        this.$refs.masterModal.title = this.$ct("add","新增")
        this.getListByLevelId()
        if (this.$refs.masterModal.add) this.$refs.masterModal.add(this.masterMdl, this.data)
      },
      // 编辑
      handleEdit: function (record, data, type, paramar) {
        this.key = '2'
        this.masterVisible = true
        this.$refs.masterModal.title =  this.$ct("edit","编辑")
        this.masterMdl = record
        this.getListByLevelId()
        if (this.$refs.masterModal.edit) this.$refs.masterModal.edit(this.masterMdl, this.data)
      },
      // 提交表单
    },
  };
</script>

<style scoped lang="less">
  .table {
    background-color: @base-bg-color;
    padding: 24px;
  }
</style>
